<template>
  <van-overlay :show="main.loginLayer" :lock-scroll="false" z-index="100">
    <div class="wrapper" @click.stop>
      <!-- 登录 -->
      <template v-if="resitre">
        <!-- 正常登录 -->
        <div
          v-if="!forget"
          class="bg-gray-800 text-white w-96 p-6 rounded-lg shadow-lg"
        >
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-center w-full">
              {{ $t("layer.login.login") }}
            </h2>
            <button class="text-gray-400 hover:text-white">
              <van-icon name="close" class="close" @click="closeLogin" />
            </button>
          </div>
          <!-- <div class="flex justify-around mb-6">
            <div
              class="cursor-pointer pb-1"
              :class="{ 'border-b-2 border-white': activeTab === 'account' }"
              @click="activeTab = 'account'"
            >
              账号登录
            </div>
            <div
              class="cursor-pointer pb-1"
              :class="{ 'border-b-2 border-white': activeTab === 'phone' }"
              @click="activeTab = 'phone'"
            >
              手机号登录
            </div>
          </div> -->
          <div v-if="activeTab === 'account'">
            <form action="">
              <label class="block mb-2"
                >{{ $t("layer.login.accont") }}
                <span class="text-red-500">*</span>
              </label>
              <input
                type="text"
                autocomplete="off"
                class="bg-[#0f212e] border border-gray-600 text-white p-2 w-full mb-4 rounded"
                placeholder=""
                v-model="accountName"
              />
              <div v-if="accountNameError" class="text-red-500 text-sm mb-4">
                {{ accountNameError }}
              </div>
              <label class="block mb-2"
                >{{ $t("layer.login.password") }}
                <span class="text-red-500">*</span></label
              >
              <div class="relative mb-4">
                <input
                  :type="accountPasswordVisible ? 'text' : 'password'"
                  autocomplete="off"
                  class="bg-[#0f212e] border border-gray-600 text-white p-2 w-full rounded"
                  placeholder=""
                  v-model="accountPassword"
                />
                <i
                  :class="
                    accountPasswordVisible ? 'fas fa-eye-slash' : 'fas fa-eye'
                  "
                  class="absolute right-3 top-3 cursor-pointer"
                  @click="toggleAccountPasswordVisibility"
                >
                  <van-icon
                    :name="accountPasswordVisible ? 'eye-o' : 'closed-eye'"
                    class="eye"
                  />
                </i>
              </div>
              <div
                v-if="accountPasswordError"
                class="text-red-500 text-sm mb-4"
              >
                {{ accountPasswordError }}
              </div>
              <button
                class="bg-green-500 text-black p-2 w-full rounded"
                @click="validateAccountForm"
              >
                {{ $t("layer.login.login") }}
              </button>
            </form>
          </div>
          <div v-if="activeTab === 'phone'">
            <form action="">
              <label class="block mb-2"
                >{{ $t("layer.login.PhoneNumber") }}
                <span class="text-red-500">*</span></label
              >
              <div class="flex mb-4">
                <select
                  class="bg-[#0f212e] border border-gray-600 text-white p-2 w-1/4 rounded-l"
                >
                  <option>+86</option>
                </select>
                <input
                  type="text"
                  autocomplete="off"
                  class="bg-[#0f212e] border border-gray-600 text-white p-2 w-3/4 rounded-r"
                  placeholder=""
                  v-model="phoneNumber1"
                />
              </div>
              <label class="block mb-2"
                >{{ $t("layer.login.password") }}
                <span class="text-red-500">*</span></label
              >
              <div class="relative mb-4">
                <input
                  :type="phonePasswordVisible ? 'text' : 'password'"
                  autocomplete="off"
                  class="bg-[#0f212e] border border-gray-600 text-white p-2 w-full rounded"
                  placeholder=""
                  v-model="phonePassword"
                />
                <i
                  :class="
                    phonePasswordVisible ? 'fas fa-eye-slash' : 'fas fa-eye'
                  "
                  class="absolute right-3 top-3 cursor-pointer"
                  @click="togglePhonePasswordVisibility"
                >
                  <van-icon
                    :name="phonePasswordVisible ? 'closed-eye' : 'eye-o'"
                    class="eye"
                  />
                </i>
              </div>
              <button
                class="bg-green-500 text-black p-2 w-full rounded"
                @click="validatePhoneForm"
              >
                {{ $t("layer.login.login") }}
              </button>
            </form>
          </div>
          <div class="text-center mt-4 flex justify-between">
            <a @click="goToForget" class="mt-2 text-green-500">{{
              $t("layer.login.ForgotPassword")
            }}</a>

            <div class="mt-2">
              <!-- {{ $t("layer.login.Donthaveanaccount") }}？ -->
              <a @click="clickrestion" class="text-green-500">{{
                $t("layer.login.registerAnAccount")
              }}</a>
            </div>
          </div>
        </div>
        <!-- 忘记密码 -->
        <div v-else>
          <div class="w-96">
            <div
              v-if="step === 1"
              class="bg-gray-800 text-white p-8 rounded-lg"
            >
              <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-center w-full">
                  {{ $t("layer.login.ChangePassword") }}
                </h2>
                <button class="text-gray-400 hover:text-white">
                  <van-icon name="close" class="close" @click="forgotClick" />
                </button>
              </div>
              <div class="mb-4">
                <label class="block mb-2">
                  {{ $t("layer.login.Email") }}
                </label>
                <div class="flex items-center mb-4">
                  <!-- <select class="bg-[#0f212e] text-white p-2 rounded-l-md">
                    <option>+86</option>
                  </select> -->
                  <input
                    type="text"
                    placeholder=""
                    v-model="email"
                    autocomplete="off"
                    @blur="validateEmail"
                    class="bg-[#0f212e] text-white p-2 w-full rounded-r-md"
                  />
                </div>
                <div class="text-sm mb-2 h-[12px]">
                  <span v-show="emailError.length > 0" class="text-red-500">
                    {{ emailError }}
                  </span>
                </div>
                <!-- <div v-if="phoneNumberError" class="text-red-500 text-sm mb-2">
                  请输入手机号
                </div>
                <div class="flex items-center">
                  <input
                    type="text"
                    placeholder=""
                    autocomplete="off"
                    class="bg-[#0f212e] text-white p-2 rounded-l-md"
                    v-model="verificationCode"
                  />
                  <button class="bg-blue-500 text-white p-2 rounded-r-md ml-2">
                    获取验证码
                  </button>
                </div>
                <div
                  v-if="verificationCodeError"
                  class="text-red-500 text-sm mb-2"
                >
                  请输入验证码
                </div> -->
              </div>
              <button
                @click="nextStep"
                class="bg-green-500 text-white p-2 w-full rounded-md"
              >
                {{ $t("layer.wallet.nextstep") }}
              </button>
            </div>
            <div
              v-if="step === 2"
              class="bg-gray-800 text-white p-8 rounded-lg"
            >
              <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-center w-full">
                  {{ $t("layer.login.ChangePassword") }}
                </h2>
                <button class="text-gray-400 hover:text-white">
                  <van-icon name="close" class="close" @click="closeLogin" />
                </button>
              </div>
              <div class="mb-4">
                <div class="mb-4">
                  <label class="block mb-2">
                    {{ $t("layer.login.EmailCode") }}
                  </label>
                  <input
                    type=""
                    placeholder=""
                    class="bg-[#0f212e] text-white p-2 w-full rounded-md"
                    v-model="emilCode"
                    autocomplete="off"
                  />
                  <div v-if="showCodeMsg" class="text-red-500 text-sm mb-2">
                    {{ $t("page.setting.emilCodeMsg") }}
                  </div>
                </div>

                <div class="mb-4">
                  <label class="block mb-2">
                    {{ $t("page.setting.newpsw") }}
                  </label>
                  <input
                    type="password"
                    placeholder=""
                    autocomplete="off"
                    class="bg-[#0f212e] text-white p-2 w-full rounded-md"
                    v-model="newPassword"
                    @input="validatePassword"
                  />
                  <ul class="text-sm mt-2">
                    <li
                      class="flex items-center"
                      :class="hasMinLength ? '' : 'text-red-500'"
                    >
                      {{ hasMinLength ? "✅" : "❌" }}

                      {{ $t("layer.login.errcode4") }}
                    </li>
                  </ul>
                </div>
                <div>
                  <label class="block mb-2">
                    {{ $t("page.setting.conformpsw") }}
                  </label>
                  <input
                    type="password"
                    placeholder=""
                    class="bg-[#0f212e] text-white p-2 w-full rounded-md"
                    v-model="confirmPassword"
                    autocomplete="off"
                    @input="validateConfirmPassword"
                  />
                  <ul class="text-sm mt-2">
                    <li
                      class="flex items-center"
                      :class="passwordsMatch ? '' : 'text-red-500'"
                    >
                      {{ passwordsMatch ? "✅" : "❌" }}

                      {{ $t("layer.login.errcode5") }}
                    </li>
                  </ul>
                </div>
              </div>
              <button
                @click="complete"
                class="bg-green-500 text-white p-2 w-full rounded-md"
              >
                {{ $t("page.setting.Submit") }}
              </button>
            </div>
          </div>
        </div>
      </template>
      <!-- 注册 -->
      <template v-else>
        <div
          class="bg-gray-800 text-white p-8 rounded-lg shadow-lg w-full max-w-md mx-4"
          style="
            max-width: 500px;
            min-width: 200px;
            max-height: calc(100% - 4em);
            overflow: auto;
          "
        >
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-center w-full">
              {{ $t("layer.login.CreateanAccount") }}
            </h2>
            <button class="text-gray-400 hover:text-white">
              <van-icon name="close" class="close" @click="closeLogin" />
            </button>
          </div>
          <div class="flex justify-between items-center mb-6">
            <button v-if="showStep" class="text-gray-400 hover:text-white">
              <van-icon
                name="arrow-left"
                @click="
                  showStep = false;
                  isScrolledToBottom = false;
                "
              />
            </button>
            <p class="..text-center w-full">
              {{ $t("layer.login.step") }} {{ !showStep ? "1" : "2" }}/2:
              {{
                !showStep ? $t("layer.login.step1") : $t("layer.login.step2")
              }}
            </p>
          </div>
          <!-- 步骤1 -->
          <form v-if="!showStep" @submit.prevent="submitFormRe">
            <!-- 正常注册 -->
            <div v-if="!quickRegister">
              <!-- 邮箱 -->
              <div class="mb-4" v-if="main.registerConfig[0]?.required">
                <label class="block mb-1" for="email">
                  {{ $t("layer.login.Email") }}
                  <span class="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  id="email"
                  v-model="email"
                  @blur="validateEmail"
                  :class="{ 'border-red-500': emailError }"
                  class="w-full p-3 bg-[#0f212e] border border-gray-600 rounded focus:outline-none focus:border-blue-500"
                />
                <small v-if="emailError" class="text-red-500">
                  {{ emailError }}
                </small>
              </div>
              <!-- 账户名 -->
              <div class="mb-4">
                <label class="block mb-1" for="username">
                  {{ $t("layer.login.accont") }}
                  <span class="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  id="username"
                  v-model="username"
                  @blur="validateUsername"
                  maxlength="14"
                  :class="{ 'border-red-500': usernameError }"
                  class="w-full p-3 bg-[#0f212e] border border-gray-600 rounded focus:outline-none focus:border-blue-500"
                />
                <small v-if="usernameError" class="text-red-500">{{
                  usernameError
                }}</small>
                <small v-else class="text-gray-400">{{
                  $t("layer.login.errcode1")
                }}</small>
              </div>
              <!-- 密码 -->
              <div class="mb-4 relative">
                <label class="block mb-1" for="password">
                  {{ $t("layer.login.password") }}
                  <span
                    v-show="main.registerConfig[0]?.required"
                    class="text-red-500"
                    >*</span
                  >
                </label>
                <div class="relative">
                  <input
                    type="password"
                    id="password"
                    v-model="password"
                    @input="validatePassword"
                    placeholder=""
                    autocomplete="off"
                    class="w-full p-3 bg-[#0f212e] border border-gray-600 rounded focus:outline-none focus:border-blue-500 pr-10"
                  />
                  <button
                    type="button"
                    class="absolute right-2 top-2 text-gray-400 hover:text-white"
                  >
                    <i class="fas fa-eye"></i>
                  </button>
                </div>
                <div class="mt-2">
                  <div class="flex items-center">
                    {{ passwordCriteria.length ? "✅" : "❌" }}
                    <span
                      class="ml-2"
                      :class="
                        passwordCriteria.length
                          ? 'text-[#16c60c]'
                          : 'text-[#f03a17]'
                      "
                      >{{ $t("layer.login.errcode4") }}</span
                    >
                  </div>
                </div>
              </div>
              <div class="mb-4 relative">
                <label class="block mb-1" for="password">
                  {{ $t("layer.login.cpassword") }}
                  <span class="text-red-500">*</span>
                </label>
                <input
                  type="password"
                  class="bg-[#0f212e] text-white p-2 w-full rounded-md"
                  v-model="confirmPassword"
                  autocomplete="off"
                  @input="validateConfirmPassword"
                />
                <ul class="text-sm mt-2">
                  <li class="flex items-center">
                    {{ passwordMatch ? "✅" : "❌" }}
                    <span
                      :class="
                        passwordMatch ? 'text-[#16c60c]' : 'text-[#f03a17]'
                      "
                      >{{ $t("layer.login.errcode5") }}</span
                    >
                  </li>
                </ul>
              </div>

              <!-- 手机号 -->
              <div v-if="main.registerConfig[1]?.show">
                <div class="mb-4 relative">
                  <label class="block mb-1" for="password">
                    {{ $t("page.setting.phoneNumber") }}
                    <span
                      v-show="main.registerConfig[1]?.required"
                      class="text-red-500"
                      >*</span
                    >
                  </label>
                  <div class="relative">
                    <span class="absolute top-[8px] left-[6px]">+234</span>
                    <input
                      class="bg-[#0f212e] pl-[46px] text-white p-2 w-full rounded-md"
                      v-model="cellPhoneNumber"
                      @input="changeCellPhoneNumber"
                    />
                  </div>
                  <ul class="text-sm mt-2">
                    <li class="flex items-center">
                      {{ cellPhoneNumberMSg ? "✅" : "❌" }}
                      <span
                        :class="
                          cellPhoneNumberMSg
                            ? 'text-[#16c60c]'
                            : 'text-[#f03a17]'
                        "
                        >{{ $t("layer.login.errcode8") }}</span
                      >
                    </li>
                  </ul>
                </div>
                <div class="mb-4 relative">
                  <label class="block mb-1" for="password">
                    {{ $t("layer.login.mobileVerificationCode") }}
                    <span class="text-red-500">*</span>
                  </label>
                  <div class="flex justify-between relative items-center">
                    <input
                      class="bg-[#0f212e] text-white p-2 w-full rounded-md"
                      v-model="phoneCode"
                    />

                    <div
                      class="absolute right-2 top-[50%] transform -translate-y-[50%] text-[#818da3]"
                      v-if="countdown > 0"
                    >
                      {{ countdown }} {{ $t("page.setting.SendAgainSeconds") }}
                    </div>
                    <div
                      v-else
                      class="absolute right-2 top-[50%] transform -translate-y-[50%] text-[#16c60c]"
                      @click="sedPhoneNumber"
                    >
                      {{ $t("page.setting.SendVerificationCode") }}
                    </div>
                  </div>
                  <ul class="text-sm mt-2">
                    <li class="flex items-center">
                      {{ phoneCodeMsg ? "✅" : "❌" }}
                      <span
                        :class="
                          phoneCodeMsg ? 'text-[#16c60c]' : 'text-[#f03a17]'
                        "
                        >{{ $t("layer.login.errcode9") }}</span
                      >
                    </li>
                  </ul>
                </div>
              </div>
              <!-- 邀请码 -->
              <div class="mb-4 relative" v-if="main.registerConfig[2]?.show">
                <label class="block mb-1" for="password"
                  >{{ $t("layer.login.code") }}
                  <span
                    v-show="main.registerConfig[2]?.required"
                    class="text-red-500"
                    >*</span
                  ></label
                >

                <div class="flex justify-between">
                  <input
                    type="text"
                    autocomplete="off"
                    v-model="invit_code"
                    :disabled="invit_codeDisabled"
                    @blur="changeInputVal"
                    class="bg-gray-800 text-white p-2 rounded-l border border-gray-700 w-full"
                  />
                </div>
              </div>

              <div class="mb-4 relative" v-if="main.registerConfig[3]?.show">
                <label class="block mb-1" for="password">
                  {{ $t("layer.login.CAPTCHA") }}
                  <span
                    class="text-red-500"
                    v-show="main.registerConfig[3]?.required"
                    >*</span
                  >
                </label>
                <div class="flex justify-between">
                  <input
                    type="text"
                    autocomplete="off"
                    v-model="code"
                    class="bg-gray-800 text-white p-2 rounded-l border border-gray-700 w-2/3"
                  />
                  <img
                    alt=""
                    :src="codeSrc"
                    @click="getCode"
                    class="w-1/4 cursor-pointer"
                  />
                </div>
              </div>

              <button
                type="submit"
                class="w-full bg-green-500 text-black p-3 rounded hover:bg-green-600"
              >
                {{ $t("layer.wallet.nextstep") }}
              </button>
            </div>
            <!-- 快速注册 没用 -->
            <div v-else>
              <div class="mb-4">
                <label class="block text-white mb-1"
                  >手机号 <span class="text-red-500">*</span></label
                >
                <div class="flex">
                  <select
                    class="bg-gray-800 text-white p-2 rounded-l border border-gray-700"
                  >
                    <option>+86</option>
                  </select>
                  <input
                    type="text"
                    autocomplete="off"
                    v-model="phone"
                    @blur="validatePhone"
                    class="bg-gray-800 text-white p-2 rounded-r border border-gray-700 w-full"
                  />
                </div>
                <small v-if="phoneError" class="text-red-500">{{
                  phoneError
                }}</small>
              </div>
              <div class="mb-4">
                <label class="block text-white mb-1"
                  >密码 <span class="text-red-500">*</span></label
                >
                <div class="relative">
                  <input
                    :type="passwordFieldType"
                    v-model="password"
                    placeholder=""
                    autocomplete="off"
                    class="bg-gray-800 text-white p-2 rounded border border-gray-700 w-full"
                  />
                  <button
                    type="button"
                    @click="togglePasswordVisibility"
                    class="absolute right-2 top-2 text-white"
                  >
                    <i :class="passwordFieldIcon"></i>
                  </button>
                </div>
              </div>
              <div class="mb-4 flex">
                <input
                  type="text"
                  autocomplete="off"
                  v-model="code"
                  class="bg-gray-800 text-white p-2 rounded-l border border-gray-700 w-2/3"
                  placeholder=""
                />
                <button
                  type="button"
                  class="bg-blue-500 text-white p-2 rounded-r w-1/3"
                >
                  获取验证码
                </button>
              </div>
              <button
                type="submit"
                class="bg-green-500 text-white p-2 rounded w-full"
              >
                继续
              </button>
            </div>
          </form>
          <!-- 步骤2 -->
          <form v-else>
            <div
              class="text-sm overflow-y-auto max-h-72 pr-2 mb-4"
              @scroll="handleScroll"
              ref="termsContent"
            >
              <h2 class="font-bold">IMPORTANT NOTICE</h2>
              <p>
                By registering on (the “Website”), you enter into a contract
                with we., and agree to be bound by (i) these Terms and
                Conditions; (ii) our Privacy Policy; (iii) our Cookies Policy
                and (iv) the rules applicable to our betting or gaming products
                as further referenced in these Terms and Conditions ("Terms and
                Conditions").
              </p>
              <p>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do
                eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
                enim ad minim veniam, quis nostrud exercitation ullamco laboris
                nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
                in reprehenderit in voluptate velit esse cillum dolore eu fugiat
                nulla pariatur. Excepteur sint occaecat cupidatat non proident,
                sunt in culpa qui officia deserunt mollit anim id est laborum.
              </p>
              <!-- Add more content to ensure scrolling -->
              <p>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do
                eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
                enim ad minim veniam, quis nostrud exercitation ullamco laboris
                nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
                in reprehenderit in voluptate velit esse cillum dolore eu fugiat
                nulla pariatur. Excepteur sint occaecat cupidatat non proident,
                sunt in culpa qui officia deserunt mollit anim id est laborum.
              </p>
              <p>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do
                eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
                enim ad minim veniam, quis nostrud exercitation ullamco laboris
                nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
                in reprehenderit in voluptate velit esse cillum dolore eu fugiat
                nulla pariatur. Excepteur sint occaecat cupidatat non proident,
                sunt in culpa qui officia deserunt mollit anim id est laborum.
              </p>
            </div>
            <div class="flex items-center mb-4">
              <input
                type="checkbox"
                autocomplete="off"
                id="accept-terms"
                v-model="isChecked"
                :disabled="!isScrolledToBottom"
                class="mr-2"
                @change="hideError"
              />
              <label for="accept-terms" class="text-sm">{{
                $t("layer.login.hasread")
              }}</label>
            </div>
            <div
              v-if="showError"
              class="text-red-500 text-sm flex items-center mb-4"
            >
              <i class="fas fa-exclamation-circle mr-2"></i>
              <span>{{ $t("layer.login.errcode6") }}</span>
            </div>
            <div
              class="bg-green-500 text-black text-center font-bold py-2 rounded cursor-pointer"
              @click="startGame"
            >
              {{ $t("layer.login.register") }}
            </div>
          </form>
          <!-- <div v-if="!showStep">
            <div class="my-4 text-center text-gray-400">或者使用</div>
            <div class="flex justify-center space-x-4">
              <a @click="quickRe">{{
                quickRegister ? "电子邮件注册" : "手机号快速注册"
              }}</a>
            </div>
          </div> -->
          <div class="text-center mt-4">
            <span class="text-gray-400">{{
              $t("layer.login.Alreadyhaveanaccount?")
            }}</span>
            <a
              href="#"
              @click="clicklog"
              class="text-blue-500 hover:underline"
              >{{ $t("layer.login.login") }}</a
            >
          </div>
        </div>
      </template>
    </div>
  </van-overlay>
  <van-overlay :show="main.registerActLayer" :lock-scroll="false" z-index="100">
    <div class="wrapper" @click.stop>
      <div
        class="flex bg-[#324e66] max-w-[400px] w-11/12 p-2 justify-between rounded-t-lg shadow-lg items-center relative"
      >
        <h2 class="text-lg text-white font-bold text-center w-full">
          {{ $t("layer.notify.registrationbonus") }}
        </h2>
        <button class="absolute right-2 top-3 text-gray-400 hover:text-white">
          <van-icon name="close" class="cross" @click="closeRgs" />
        </button>
      </div>
      <div
        class="bg-[#213744] max-w-[400px] text-white w-11/12 p-6 pt-4 rounded-b-lg shadow-lg"
      >
        <div class="gold-bg">
          <div class="gold-img"></div>
          <p class="num w-fit whitespace-nowrap overflow-hidden">
            + {{ registerNum }}
          </p>
        </div>
        <!-- 内容 -->
        <p class="my-5 text-[#919bb1]">
          {{ $t("layer.register.con1") }} {{ registerNum }}
          {{ $t("layer.register.con2") }}
        </p>
        <!-- 按钮 -->
        <button
          class="bg-[#1475e1] hover:bg-[#105eb4] text-white p-2 block w-32 m-auto rounded mt-4"
          @click="closeRgs"
        >
          {{ $t("layer.wallet.confirm") }}
        </button>
      </div>
    </div>
  </van-overlay>
  <lightreminder ref="toast"></lightreminder>
  <!-- <mongolianlayer v-if="ladingdemoe"></mongolianlayer> -->
</template>

<script setup>
import { ref, onMounted, watch, computed, getCurrentInstance } from "vue";
import { ElNotification } from "element-plus";
import { mainAct } from "../../store/activeda";
import { mainWallet } from "../../store/wallet";
import {
  userRegister,
  userLogin,
  getCaptcha,
  checkCaptcha,
  init,
  getUserExists,
  postUserEmial,
  postUserEmiaSendl,
  postUserForgoPassword,
  postUserPhoneSend,
  postUserPhoneCheckGetCode,
  postUserSmsCodeCheck
} from "../../api/user.js";
import { activeRegister } from "../../api/active.js";
import { getBalance } from "../../api/wallet.js";
import { msgRegister } from "../../api/msg.js";
import { eventBus } from "@/utils/eventBus";

const {
  appContext: {
    config: { globalProperties }
  }
} = getCurrentInstance();

const toast = ref(null);
const main = mainAct();
const main2 = mainWallet();
const registerNum = ref(null);

const invit_code = ref("");
const getCodeFromUrl = url => {
  const urlObj = new URL(url);
  const params = new URLSearchParams(urlObj.search);
  return params.get("code");
};
let invit_codeDisabled = ref(false);
onMounted(async () => {
  await getCode();
  let hear = window.location.href;
  if (hear.includes("code")) {
    invit_codeDisabled.value = true;
    invit_code.value = getCodeFromUrl(window.location.href);
    main.invit_code = invit_code.value;
  } else {
    invit_codeDisabled.value = false;
    if (main && main.invit_code?.length) {
      invit_code.value = main.invit_code;
    }
  }
});

const changeInputVal = val => {
  main.invit_code = invit_code.value;
};

const codeSrc = ref("");
const codeId = ref(null);
const getCode = async () => {
  let res = await getCaptcha();
  // console.log(res);
  codeSrc.value = res.data.img;
  codeId.value = res.data.id;
  // console.log(codeSrc.value);
};
const props = defineProps(["modelshow"]);
const emit = defineEmits(["cloeselogin"]);

const forgotClick = () => {
  forget.value = false;
  step.value = 1;
  cleardata();
};

const closeLogin = () => {
  console.log("closeLogin");
  //刷新验证码
  getCode();
  //处理勾选协议状态
  isChecked.value = false;
  isScrolledToBottom.value = false;
  // history.replaceState({}, "", window.location.pathname);
  emit("cloeselogin");
  // forget.value = true; //切换为login页

  cleardata(); //清空输入框
  // socloeshoe();
  if (intervalId.value) {
    clearInterval(intervalId.value); // 如果已经有一个定时器在运行，先清除它
  }
};
const closeRgs = () => {
  main.registerActLayer = false;
};
const quickRegister = ref(false);
const quickRe = () => {
  showStep.value = false; //步骤1
  quickRegister.value = !quickRegister.value;
};
const cleardata = () => {
  showStep.value = false;
  forget.value = false;
  isChecked.value = false;
  step.value = 1;
  verificationCode.value = "";
  newPassword.value = "";
  confirmPassword.value = "";
  accountName.value = "";
  accountPassword.value = "";
  phoneNumber1.value = "";
  email.value = "";
  phone.value = "";
  username.value = "";
  password.value = "";
  code.value = "";
  dobDay.value = "";
  dobMonth.value = "";
  dobYear.value = "";
  phoneCode.value = "";
  phoneNumber.value = "";
  promoCode.value = "";
  emilCode.value = "";
};

/* 忘记密码 */
const forget = ref(false);
const step = ref(1);
// const phoneNumber = ref("");
const verificationCode = ref("");
const newPassword = ref("");
const confirmPassword = ref("");
const emilCode = ref("");

const phoneNumberError = ref(false);
const verificationCodeError = ref(false);

const goToForget = () => {
  forget.value = true;
};

// 匹配英文字母
const hasUpperLower = computed(
  () => /[a-z]/.test(newPassword.value) && /[A-Z]/.test(newPassword.value)
);
const hasNumber = computed(
  () => /\d/.test(newPassword.value) && newPassword.value.length >= 6
);
const hasMinLength = computed(() => newPassword.value.length >= 6);
const passwordsMatch = computed(
  () => newPassword.value === confirmPassword.value
);
const passwordMatch = computed(
  () => password.value === confirmPassword.value && confirmPassword.value != ""
);
const cellPhoneNumberMSg = ref(false);

const phoneCodeMsg = computed(() => phoneCode.value && phoneCode.value != "");

const validateConfirmPassword = () => {};

// 校验手机号
const changeCellPhoneNumber = () => {
  let reg = /[789]{1}\d{9}$/;
  console.log("cellPhoneNumber.value", cellPhoneNumber.value);
  if (reg.test(cellPhoneNumber.value)) {
    cellPhoneNumberMSg.value = true;
  } else {
    cellPhoneNumberMSg.value = false;
  }
};

const nextStep = async () => {
  // validateEmail();
  const emailPattern = /^[a-zA-Z0-9_.%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
  emailError.value = emailPattern.test(email.value)
    ? ""
    : globalProperties.$t("layer.login.EmailErrcode");
  if (emailError.value.length) {
  } else {
    phoneNumberError.value = !phoneNumber.value;
    verificationCodeError.value = !verificationCode.value;

    const res = await postUserEmiaSendl({
      email: email.value
    });

    if (res.errno == 0) {
      step.value = 2;
    }
  }
};

const showCodeMsg = ref(false);
const complete = async () => {
  console.log("emilCode.value", emilCode.value);
  console.log("hasUpperLower.value", hasUpperLower.value);
  console.log("hasNumber.value", hasNumber.value);
  console.log("hasMinLength.value", hasMinLength.value);
  console.log("passwordsMatch.value", passwordsMatch.value);

  if (!emilCode.value.length) return (showCodeMsg.value = true);
  showCodeMsg.value = false;
  // hasUpperLower.value &&
  if (hasNumber.value && hasMinLength.value && passwordsMatch.value) {
    // alert("密码修改成功");
    const res = await postUserForgoPassword({
      code: emilCode.value,
      password: newPassword.value,
      password_confirm: confirmPassword.value
    });
    if (res.errno == 0) {
      resitre.value = true;
      forget.value = false;
      step.value = 1;
      email.value = "";
      emilCode.value = "";
      newPassword.value = "";
      confirmPassword.value = "";
      let msg = globalProperties.$t("page.setting.alterPwd");
      ElNotification({
        position: "top-left",
        zIndex: 1004,
        title: "Success",
        message: msg,
        type: "success"
      });
    }
  }
  // else {
  //   alert("请确保所有条件都满足");
  // }
};

/* 玩家登录 */
const activeTab = ref("account");
const accountName = ref("");
const accountPassword = ref("");
const phoneNumber1 = ref("");
const phonePassword = ref("");
const accountNameError = ref("");
const accountPasswordError = ref("");
const accountPasswordVisible = ref(false);
const phonePasswordVisible = ref(false);

const validateAccountForm = event => {
  event.preventDefault(); // 阻止表单提交
  accountNameError.value = "";
  accountPasswordError.value = "";
  if (accountName.value.length < 3 || accountName.value.length > 14) {
    accountNameError.value = globalProperties.$t("layer.login.errcode1");
    return;
  }

  const passwordRegex = /^.{6,}$/;
  console.log("执行");
  if (!passwordRegex.test(accountPassword.value)) {
    accountPasswordError.value = globalProperties.$t("layer.login.errcode7");
    return;
  }

  postlogin({ user_name: accountName.value, password: accountPassword.value });
  // closeLogin();
};

const validatePhoneForm = () => {
  // Add phone form validation if needed
};

const toggleAccountPasswordVisibility = () => {
  accountPasswordVisible.value = !accountPasswordVisible.value;
};

const togglePhonePasswordVisibility = () => {
  phonePasswordVisible.value = !phonePasswordVisible.value;
};
/* 玩家注册 */

const resitre = computed(() => {
  return main._resitre;
});

const clickrestion = () => {
  // resitre.value = false;
  // main.loginLayer = true;
  main.showRegister();
  console.log("点击clickrestion", resitre.value);

  main.getCommonRegisterIsFee();

  if (intervalId.value) {
    countdown.value = 0;
    intervalId.value = null; // 将定时器 ID 重置为 null
    clearInterval(intervalId.value); // 如果已经有一个定时器在运行，先清除它
  }
  // main.getvcode();
};

const clicklog = () => {
  main.showLoginLayer("no");
  // main.getvcode();123456Aa
};
const email = ref("");
const phone = ref("");
const username = ref("");
const password = ref("");
const code = ref("");
const dobDay = ref("");
const dobMonth = ref("");
const dobYear = ref("");
const phoneCode = ref("");
const phoneNumber = ref("");
const promoCode = ref(false);
const emailError = ref("");
const phoneError = ref("");
const usernameError = ref("");
const months = ref([
  "1月",
  "2月",
  "3月",
  "4月",
  "5月",
  "6月",
  "7月",
  "8月",
  "9月",
  "10月",
  "11月",
  "12月"
]);
const cellPhoneNumber = ref("");

const passwordCriteria = ref({
  upperLower: false,
  number: false,
  length: false
});

const validateEmail = () => {
  const emailPattern = /^[a-zA-Z0-9_.%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
  emailError.value = emailPattern.test(email.value)
    ? ""
    : globalProperties.$t("layer.login.EmailErrcode");
  console.log("validateEmail", emailError.value);
};
const codeErr = ref(false);
const validateCode = async () => {
  let value = {
    id: codeId.value,
    code: code.value
  };
  let res = await checkCaptcha(value);
  if (res.data.valid != 1) {
    codeErr.value = false;
    getCode();
    ElNotification({
      position: "top-left",
      zIndex: 1004,
      title: "Error",
      message: "Please enter the correct verification code",
      type: "error"
    });
  } else {
    codeErr.value = true;
  }
  console.log(res);
};

const validateUsername = () => {
  usernameError.value =
    username.value.length >= 3 && username.value.length <= 14
      ? ""
      : globalProperties.$t("layer.login.errcode1");
  console.log("username.value---", username.value);
};

const validatePassword = () => {
  // passwordCriteria.value.upperLower =
  //   /[a-z]/.test(password.value) && /[A-Z]/.test(password.value);
  // passwordCriteria.value.number = /\d/.test(password.value);
  passwordCriteria.value.length = password.value.length >= 6;
};

const submitFormRe = async () => {
  if (emailError.value.length) return;
  if (usernameError.value.length) return;

  // 邮箱
  if (main.registerConfig[0]?.required && email.value == "") {
    console.log("邮箱退出");
    return false;
  }
  // 手机
  if (
    main.registerConfig[1]?.required &&
    (cellPhoneNumber.value == "" || phoneCode.value == "")
  ) {
    console.log("手机退出");
    return false;
  }

  // 推荐码
  if (main.registerConfig[2]?.required && invit_code.value == "") {
    console.log("推荐码退出");
    return false;
  }

  if (main.registerConfig[3]?.required && code.value == "") {
    console.log("验证码退出");
    return false;
  }
  if (username.value == "" || confirmPassword.value == "") {
    console.log("必填未通过");
    return false;
  }
  if (showStep) {
    //电邮注册
    if (main.registerConfig[3]?.required) {
      await validateCode();
    }
    if (main.registerConfig[1]?.required) {
      changeCellPhoneNumber();
    }
    validatePassword();
    console.log("passwordCriteria", passwordCriteria.value);
    console.log("passwordMatch", passwordMatch.value);
    console.log("codeErr", codeErr.value);
    codeErr.value = main.registerConfig[3]?.required ? codeErr.value : true;
    if (passwordCriteria.value.length && passwordMatch.value && codeErr.value) {
      console.log({
        user_name: username.value,
        password: password.value,
        password_confirm: confirmPassword.value,
        verify_code: code.value,
        verify_code_id: codeId.value,
        email: email.value,
        phone_code: phoneCode.value,
        phone: cellPhoneNumber.value
      });
      console.log("下一步");
      let res = await getUserExists({ user_name: username.value });
      let emialRes =
        main.registerConfig[0]?.required &&
        (await postUserEmial({ email: email.value }));

      // 当设置手机短信必填时 需要校验
      if (main.registerConfig[1]?.required) {
        let phoneMsg = await postUserPhoneCheckGetCode({
          phone: cellPhoneNumber.value
        });

        if (phoneMsg.data.is_exist) {
          return ElNotification({
            position: "top-left",
            zIndex: 1004,
            title: "Error",
            message: globalProperties.$t("layer.login.phoneNumberAlready"),
            type: "error"
          });
        }

        let phoneCodeRes = await postUserSmsCodeCheck({
          phone: cellPhoneNumber.value,
          code: phoneCode.value
        });

        if (phoneCodeRes.errno != 0) {
          return;
        }
      }

      if (emialRes?.data?.is_exist)
        return ElNotification({
          position: "top-left",
          zIndex: 1004,
          title: "Error",
          message: globalProperties.$t("layer.wallet.userEmila"),
          type: "error"
        });
      if (
        res.errno == 0 &&
        res.data.existed == 0 &&
        !emialRes?.data?.is_exist
      ) {
        goToStep2();
      } else {
        ElNotification({
          position: "top-left",
          zIndex: 1004,
          title: "Error",
          message: globalProperties.$t("layer.wallet.userName"),
          type: "error"
        });
      }
    }
  } else {
    //快速注册
    await validateCode();
    // console.log(codeErr.value);
    if (codeErr.value) {
      console.log({
        user_name: username.value,
        password: password.value,
        password_confirm: confirmPassword.value,
        verify_code: code.value,
        verify_code_id: codeId.value
      });
      console.log("验证拦截");
      // goToStep2();
    }
  }
};
const showStep = ref(false);
const goToStep2 = () => {
  showStep.value = true;
};
//注册step2
const isChecked = ref(false);
const showError = ref(false);
const isScrolledToBottom = ref(false);
const termsContent = ref(null);
const handleScroll = () => {
  const element = termsContent.value;
  // console.log((element.scrollHeight - element.scrollTop)* 0.8);
  // console.log(element.clientHeight);
  if ((element.scrollHeight - element.scrollTop) * 0.8 < element.clientHeight) {
    console.log("滚动到底");
    isScrolledToBottom.value = true;
  }
};

const hideError = () => {
  if (isChecked.value) {
    showError.value = false;
  } else {
    showError.value = true;
  }
};

const startGame = async () => {
  if (!isChecked.value) {
    showError.value = true;
  } else {
    showError.value = false;
    // alert("开始游戏");
    let data = {
      user_name: username.value,
      password: password.value,
      password_confirm: confirmPassword.value,
      verify_code: code.value,
      verify_code_id: codeId.value,
      invit_code: main.invit_code,
      email: email.value,
      phone_code: phoneCode.value,
      phone: cellPhoneNumber.value
    };
    console.log(data);
    let res = await userRegister(data);
    if (res.errno == 0) {
      main.invit_code = "";
      resitre.value = true;
      ElNotification({
        position: "top-left",
        zIndex: 1004,
        message: globalProperties.$t("page.active.registerSucceeded"),
        type: "success"
      });
      main.loginLayer = false;
      //弹窗注册 如果成功
      let res2 = await activeRegister();
      // console.log(res2);
      if (res2.errno == 0) {
        postlogin({ user_name: username.value, password: password.value });
        closeLogin();
        // 如果是空对象就不弹出活动弹窗
        if (Object.keys(res2.data).length === 0) return;
        registerNum.value = res2.data.bonus_amount;
        main.registerActLayer = true;
      }

      return;
    } else {
      // ElNotification({
      //   position: "top-left",
      //   zIndex: 1004,
      //   title: "Error",
      //   message: res.msg,
      //   type: "error"
      // });
      return;
    }
  }
};

const postlogin = async val => {
  console.log(val);
  let res = await userLogin(val);
  console.log(res);
  if (res?.errno == 0) {
    // 过期时间7天
    // var time = 604800000; //1000*60*60*24*7;
    // var time = 6000; //1000*60*60*24*7;
    // var storage = window.localStorage;
    // var oldTimestamp = storage.getItem("timestamp"); //以前存的时间戳
    // if (oldTimestamp) {
    //   var nowTimestamp = new Date().getTime(); //当前时间戳
    //   // 如果当前时间戳> 前面存的时间戳+过期时间 表示已经过期
    //   var sumTimestamp = timestamp + time;
    //   if (nowTimestamp > sumTimestamp) {
    //     console.log("登录时间已过期");
    //     storage.clear();
    //     main.isLogin = false;

    //   }
    // }
    main.isLogin = true;
    main.token = res.data.token;
    main.user_detail = res.data.user_detail;
    eventBus.emit("showActiveProp");
    // ElNotification({
    //   position: "top-left",
    //   zIndex: 1004,
    //   title: "Success",
    //   message: "Login succeeded",
    //   type: "success"
    // });
    if (main.user_detail.payment_password_set == 0) {
      ElNotification({
        position: "top-right",
        duration: 0,
        zIndex: 1004,
        title: globalProperties.$t("layer.wallet.tip"),
        message: globalProperties.$t("layer.wallet.plzSetFst"),
        type: "warning"
      });
    }
    closeLogin();
    // getWallet();
    eventBus.emit("tigger");
    return;
  } else {
    return;
  }
};
const getWallet = async () => {
  return;
  let res = await getBalance();
  if (res.data.balance) {
    // main2.balance = res.data.balance;
  }
};

const countdown = ref(0);
const intervalId = ref(null); // 使用 null 初始值，因为 setInterval 返回的是一个数字

const startCountdown = () => {
  if (intervalId.value) {
    clearInterval(intervalId.value); // 如果已经有一个定时器在运行，先清除它
  }
  countdown.value = 60;
  intervalId.value = setInterval(() => {
    // 存储新的定时器 ID
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(intervalId.value); // 清除定时器
      intervalId.value = null; // 将定时器 ID 重置为 null
    }
  }, 1000);
};

const sedPhoneNumber = () => {
  let msg = globalProperties.$t("layer.login.errcode8");
  console.log("cellPhoneNumberMSg", cellPhoneNumberMSg);
  if (!cellPhoneNumberMSg.value)
    return ElNotification({
      position: "top-left",
      zIndex: 1004,
      title: "Error",
      message: msg,
      type: "error"
    });
  postUserPhoneSend({ phone: cellPhoneNumber.value })
    .then(res => {
      if (res.errno == 0) {
        startCountdown();
      }
    })
    .catch(err => {});
};

defineExpose({ clickrestion, clicklog });
</script>

<style lang="less" scoped>
.wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  .gold-bg {
    width: 132px;
    height: 120px;
    margin: auto;
    background-image: url("../../assets/checkin/d1.png");
    background-size: 100% 100%;
    position: relative;
    .gold-img {
      position: absolute;
      left: 50%;
      top: 20px;
      transform: translateX(-50%);
      width: 60px;
      height: 50px;
      background-image: url("../../assets/checkin/j.png");
      background-size: 100% 100%;
    }
    .num {
      position: absolute;
      bottom: 6px;
      left: 50%;
      transform: translateX(-50%);
      font-size: 16px;
    }
  }
}
</style>
